/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This class contains the fragment responsible for displaying a user's holds.
 */

package us.in.lib.acpl.Mobile_ACPL;

import java.util.ArrayList;
import java.util.List;

import com.google.analytics.tracking.android.EasyTracker;


import us.in.lib.acpl.Mobile_ACPL.adapters.HoldListAdapter;
import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.patron.Hold;
import us.in.lib.acpl.Mobile_ACPL.ws.AccountInfoHandler;
import us.in.lib.acpl.Mobile_ACPL.ws.CancelHoldsHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class AccountHoldsFragment extends ListFragment {

	private AccountHoldsFragment thisFragment = this;
	private boolean selected[] = new boolean[0];
	private boolean noHolds = false;
	List<Hold> holds;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		RelativeLayout fragView = (RelativeLayout) inflater.inflate(
				R.layout.account_holds, container, false);
		fragView.findViewById(R.id.cancelHoldsButton).setOnClickListener(
				new ButtonListener());
		fragView.findViewById(R.id.holdsSelectAllBox).setOnClickListener(
				new CheckBoxListener());

		if (noHolds) {
			fragView.findViewById(R.id.noHolds).setVisibility(View.VISIBLE);
		}
		return fragView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		this.getListView().setOnItemClickListener(new ListListener());

	}

	public void setList() {

		AccountActivity act = (AccountActivity) getActivity();
		AccountInfoHandler handler = act.getAccHandler();
		holds = handler.getHolds();

		if (this.getListAdapter() == null) {

			selected = new boolean[holds.size()];
			System.out.println(selected.length);
			this.setListAdapter(new HoldListAdapter(this.getActivity(), holds,
					selected));
		} else {
			HoldListAdapter ad = (HoldListAdapter) this.getListAdapter();
			for (int i = 0; i < selected.length; i++) {
				selected[i] = false;
			}
			ad.notifyDataSetChanged();

		}

		if (holds.size() == 0) {

			View v = getActivity().findViewById(R.id.noHolds);

			this.noHolds = true;
			if (v != null) {
				v.setVisibility(View.VISIBLE);
			}
		}
	}

	public void handleCancellationResult(boolean success, List<Hold> toCancel) {
		getActivity().findViewById(R.id.accountBar).setVisibility(View.GONE);
		// show dialog
		if (success) {
			String text = "" + toCancel.size() + " hold(s) cancelled";
/*			Toast toast = Toast.makeText(getActivity(), text,
					Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();*/
			
			new AlertDialog.Builder(this.getActivity()).setTitle("Cancel Holds")
			.setMessage("\n"+text+"\n").setPositiveButton("OK", new android.content.DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					arg0.dismiss();
				}


				
			}).create().show();
			
			
			AccountActivity act = (AccountActivity) getActivity();
			act.getAccHandler().getHolds().removeAll(toCancel);

			selected = new boolean[act.getAccHandler().getHolds().size()];
			for (int i = 0; i < selected.length; i++) {
				selected[i] = false;
			}
			HoldListAdapter ad = (HoldListAdapter) this.getListAdapter();
			ad.setSelected(selected);
			ad.notifyDataSetChanged();

			CheckBox c = (CheckBox) this.getView().findViewById(
					R.id.holdsSelectAllBox);
			c.setChecked(false);
			if (act.getAccHandler().getHolds().size() == 0) {
				noHolds = true;
				getActivity().findViewById(R.id.noHolds).setVisibility(
						View.VISIBLE);
			}
		} else {
			
			new AlertDialog.Builder(this.getActivity()).setTitle("Cancel Holds")
			.setMessage("\nCancellation failed\n").setPositiveButton("OK", new android.content.DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					arg0.dismiss();
				}


				
			}).create().show();
/*			Toast toast = Toast.makeText(getActivity(), "Cancellation failed.",
					Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();*/
		}

	}

	private class ButtonListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			getActivity().findViewById(R.id.accountBar).setVisibility(
					View.VISIBLE);
			AccountActivity act = (AccountActivity) getActivity();
			CancelHoldsHandler handler = new CancelHoldsHandler(thisFragment);
			ArrayList<Hold> toCancel = new ArrayList<Hold>();

			for (int i = 0; i < selected.length; i++) {
				if (selected[i]) {
					toCancel.add(act.getAccHandler().getHolds().get(i));
				}
			}
			handler.cancel(toCancel);
			

			EasyTracker.getTracker().sendEvent("Holds", "Cancel Holds Button Pressed", null, null);

		}

	}

	private class CheckBoxListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			CheckBox c = (CheckBox) arg0;
			boolean checked = c.isChecked();
			for (int i = 0; i < selected.length; i++) {
				if (checked) {
					if(!(holds.get(i).isAvailable())){
						selected[i] = true;
					}		
				} else {
					selected[i] = false;
				}
				HoldListAdapter ad = (HoldListAdapter) getListAdapter();
				ad.notifyDataSetChanged();
			}
		}

	}

	private class ListListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> viewGroup, View view,
				int position, long id) {
			boolean available = holds.get(position).isAvailable();
			if(!available){
				CheckBox c = (CheckBox) view
						.findViewById(R.id.selectForCancellationBox);
				boolean checked = c.isChecked();
				if (checked) {
					c.setChecked(false);
					selected[position] = false;
				} else {
					c.setChecked(true);
					selected[position] = true;
				}

			}

		}

	}

}
